<template>
  <el-dialog :visible="visible" center :show-close="false" width="1280px">
    <div class="b g3 f16 tl" slot="title">
      <div class="ks-row-between pl15 pr15">
        <span>{{ formType === 1 ? $t("sys.new_template") : $t("sys.edit_template") }}</span>
        <span class="el-icon-close g9 f26 poi" @click="handleCancel"></span>
      </div>
    </div>

    <el-form class="pl30 pr30" :model="form" ref="form" label-width="100px">
      <el-form-item
        :label="$t('sys.template_name')"
        prop="name"
        :rules="[
          {
            required: true,
            message: $t('sys.template_name_not_null'),
          },
        ]"
      >
        <el-input
          style="width: 400px"
          v-model="form.name"
          :maxlength="64"
          show-word-limit
        />
      </el-form-item>

      <el-table :data="mockTableData" stripe border>
        <template v-for="(item, index) in form.templates">
          <el-table-column :key="index" :label="header[index]">
            <template slot-scope="scope">
              <el-form-item
                label=""
                label-width="0px"
                :prop="'templates.' + scope.$index + '.shiftsId'"
              >
                <el-select
                  style="width: 100%"
                  clearable
                  v-model="item.shiftsId"
                  @change="
                    (val) => {
                      onShiftSelect(val, scope.row);
                    }
                  "
                >
                  <el-option
                    v-for="item in shifts"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <!--      </el-form-item>-->
    </el-form>
    <div slot="footer" class="tr">
      <el-button @click="handleCancel">{{$t('sys.cancel')}}</el-button>
      <el-button :loading="confirmLoading" type="primary" @click="handleSubmit"
        >{{$t('sys.confirm')}}</el-button
      >
    </div>
  </el-dialog>
</template>

<script>
import { cloneDeep } from "lodash";

import i18n from "../../../../i18n"
import { getHmshiftsList } from '@/apis/paas/HmShiftsController.js'
import { putHmusershiftsconfig,postHmusershiftsconfig } from '@/apis/paas/HmUserShiftsConfigController.js'
export default {
  name: "ShiftTempForm",
  components: {},
  data() {
    return {
      header: [i18n.t('sys.Monday'), i18n.t('sys.Tuesday'), i18n.t('sys.Wednesday'), i18n.t('sys.Thursday'), i18n.t('sys.Friday'), i18n.t('sys.Saturday'), i18n.t('sys.Sunday')],
      shifts: [],
      visible: false,
      loading: false,
      confirmLoading: false,
      form: {
        templates: [
          { shiftsId: "", type: "mon" },
          { shiftsId: "", type: "tue" },
          { shiftsId: "", type: "wed" },
          { shiftsId: "", type: "thu" },
          { shiftsId: "", type: "fri" },
          { shiftsId: "", type: "sat" },
          { shiftsId: "", type: "sun" },
        ],
      },
      formType: 1, // 1-新增 2-编辑
      mockTableData: [{}],
      id: 0,
    };
  },
  computed: {},
  watch: {
    id(val) {},
  },
  created() {},
  mounted() {
    const { id } = this.$store.getters.getUserVal;
    getHmshiftsList({ userId: id }).then((res) => {
      this.shifts = res || [];
      if (res.length === 0) {
        this.$notify({
          title: this.$t("sys.error"),
          message: this.$t("sys.unable_to_get_shift information_set_shift"),
          type: "warning",
        });
      }
    });
  },
  methods: {
    add() {
      this.formType = 1;
      this.id = 0;
      this.visible = true;
      this.form = {
        templates: [
          { shiftsId: "", type: "mon" },
          { shiftsId: "", type: "tue" },
          { shiftsId: "", type: "wed" },
          { shiftsId: "", type: "thu" },
          { shiftsId: "", type: "fri" },
          { shiftsId: "", type: "sat" },
          { shiftsId: "", type: "sun" },
        ],
      };
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
      });
    },

    edit(record) {
      this.form = {
        ...record,
      };
      // const { id, name, data } = record
      // this.tableData = cloneDeep(data)

      // this.id = id
      this.formType = 2;
      this.visible = true;
      this.$nextTick(() => {
        this.$refs.form.clearValidate();
        // this.form.setFieldsValue({ name })
      });
    },
    getHmshiftsList() {},
    onShiftSelect(val, record) {
      // this.$set(record, 'shiftsId', val)
      // this.$set(this.form.data[index], 'shiftsId', val)
      // this.$set(this.tableData, date, { ...this.tableData[0], [date]: { shiftsId: val } })
    },

    convertData() {
      const data = [];
      for (const prop in this.tableData[0]) {
        const item = this.tableData[0];
        if (item.hasOwnProperty(prop)) {
          if (prop !== "id") {
            data.push({
              id: item[prop].id || 0,
              shiftsId: item[prop].shiftsId,
              type: prop,
            });
          }
        }
      }
      return data;
    },

    async handleSubmit() {
      try {
        await this.$refs.form.validate();
        const { id, name, templates } = this.form;
        const templatesData = templates.map((item) => {
          return {
            id: item.id || 0,
            shiftsId: item.shiftsId,
            type: item.type,
          };
        });
        let params = {};
        let request = null;
        if (this.formType === 1) {
          params = { name, templates: templatesData, enable: false };
          request = postHmusershiftsconfig;
        } else {
          params = {
            id,
            name,
            templates: templatesData,
          };
          request = putHmusershiftsconfig;
        }

        for (const key in params) {
          params[key] =
            typeof params[key] === "string" ? params[key].trim() : params[key];
        }
        this.confirmLoading = true;
        request(params)
          .then((res) => {
            this.handleCancel();
            this.$emit("ok");
          })
          .finally(() => {
            this.confirmLoading = false;
          });
      } catch (error) {
        console.log(error);
      }
    },

    handleCancel() {
      this.resetForm();
      this.visible = false;
    },

    resetForm() {
      // this.form.setFieldsValue({ name: '' })
      this.tableData = [
        {
          id: 0,
          mon: {
            shiftsId: "",
          },
          tue: {
            shiftsId: "",
          },
          wed: {
            shiftsId: "",
          },
          thu: {
            shiftsId: "",
          },
          fri: {
            shiftsId: "",
          },
          sat: {
            shiftsId: "",
          },
          sun: {
            shiftsId: "",
          },
        },
      ];
    },
  },
};
</script>
